﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.Practices.Unity;
using Vit.Common;
using Vit.Common.Extensions;
using Vit.Web.Providers;

namespace Vit.Web.Mvc.Controllers
{
    public class CaptchaController : Controller
    {
        private string AllowedChars = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789";
        private int Length = 5;

        public ActionResult Get()
        {
            int width = 150;
            int height = 120;
            IRandomTextGenerator random = Unity.Current.Resolve<IRandomTextGenerator>();
            ICaptchaGenerator captcha = Unity.Current.Resolve<ICaptchaGenerator>();
            string randomText = random.Generate(AllowedChars, Length);
            Bitmap img = captcha.Generate(randomText, width, height);
            MemoryStream stream = new MemoryStream();
            img.Save(stream, ImageFormat.Jpeg);
            return new FileContentResult(stream.ToArray(), "image/jpeg");
        }

        public ActionResult Verify(string id)
        {
            ICaptchaGenerator captcha = Unity.Current.Resolve<ICaptchaGenerator>();
            bool verified = captcha.Verify(id);
            return Json(verified, JsonRequestBehavior.AllowGet);
        }
    }
}
